

function myPromiseAllSettled(promises) {
    return new Promise(((resolve, reject) => {
        if (promises === null || typeof promises[Symbol.iterator] !== "function") {
            throw new Error("不可迭代")
        }
        if (promises.length === 0) {
            resolve([])
        }
        //? 返回的数组中包含了每个 Promise 对象的执行结果，无论是成功还是失败
        let values = []
        let count = 0
        let finished = 0
        promises.forEach((promise,index) => {
            count = index + 1
            Promise.resolve(promise).then(res => {
                finished++
                values[index] = {
                    status : 'fulfilled',
                    value : res
                }
            },err => {
                finished++
                values[index] = {
                    status: 'rejected',
                    value : err
                }
            }).finally(() => {
                //? 这个新的 Promise 对象会在数组中所有的 Promise 对象都执行完毕后(所以依靠finally和if函数)才会被 resolved
                if (count <= finished) {
                    resolve(values)
                }
            })
        })
    }))
}


const pro = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(3);
    }, 1000);
});

Promise.allSettled([pro, Promise.resolve(1), Promise.reject(2)]).then(
    (data) => {
        console.log(data);
    }
);

myPromiseAllSettled([pro, Promise.resolve(1), Promise.reject(2)]).then(
    (data) => {
        console.log(data);
    }
);
